import prisma from '../lib/prisma';
import { hashPassword } from '../utils/auth';

// 用户相关类型定义
export interface User {
  id: number;
  username: string;
  email: string | null;
  password: string;
  role: string;
  status: boolean;
  mobile: string | null;
  lastLogin: Date | null;
  display: boolean;
  deleteBy: number | null;
  deleteAt: Date | null;
  createdAt: Date;
  updatedAt: Date;
}

export interface CreateUserRequest {
  username: string;
  email?: string;
  password: string;
  role?: string;
  status?: boolean;
}

export interface UpdateUserRequest {
  username?: string;
  email?: string;
  password?: string;
  role?: string;
  status?: boolean;
}

export interface UserQueryParams {
  page?: number;
  limit?: number;
  keyword?: string;
  role?: string;
  status?: boolean;
}

export interface PaginatedUsers {
  users: User[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

export class UserService {
  // 获取所有用户（分页）
  async getUsers(params: UserQueryParams = {}): Promise<PaginatedUsers> {
    try {
      const {
        page = 1,
        limit = 10,
        keyword,
        role,
        status,
      } = params;

      const skip = (page - 1) * limit;

      // 构建查询条件
      const where: any = {
        display: true, // 只显示未软删除的数据
      };

      if (keyword) {
        where.OR = [
          { username: { contains: keyword, mode: 'insensitive' } },
          { email: { contains: keyword, mode: 'insensitive' } },
        ];
      }

      if (role) {
        where.role = role;
      }

      if (status !== undefined) {
        where.status = status;
      }

      // 执行查询
      const [users, total] = await Promise.all([
        prisma.user.findMany({
          where,
          skip,
          take: limit,
          orderBy: { createdAt: 'desc' },
          select: {
            id: true,
            username: true,
            email: true,
            role: true,
            status: true,
            mobile: true,
            lastLogin: true,
            display: true,
            deleteBy: true,
            deleteAt: true,
            createdAt: true,
            updatedAt: true,
          },
        }),
        prisma.user.count({ where }),
      ]);

      return {
        users: users as User[],
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      };
    } catch (error) {
      console.error('获取用户列表失败:', error);
      throw new Error('获取用户列表失败');
    }
  }

  // 根据ID获取用户
  async getUserById(id: number): Promise<User | null> {
    try {
      const user = await prisma.user.findFirst({
        where: {
          id,
          display: true, // 只显示未软删除的数据
        },
        select: {
          id: true,
          username: true,
          email: true,
          password: true,
          role: true,
          status: true,
          display: true,
          deleteBy: true,
          deleteAt: true,
          createdAt: true,
          updatedAt: true,
          lastLogin: true,
        },
      });

      return user as User | null;
    } catch (error) {
      console.error('获取用户详情失败:', error);
      throw new Error('获取用户详情失败');
    }
  }

  // 根据用户名获取用户（用于登录验证）
  async getUserByUsername(username: string): Promise<User | null> {
    try {
      const user = await prisma.user.findFirst({
        where: {
          OR: [
            { username: username },
            { email: username },
          ],
          display: true, // 只显示未软删除的数据
        },
        select: {
          id: true,
          username: true,
          email: true,
          password: true,
          role: true,
          status: true,
          display: true,
          deleteBy: true,
          deleteAt: true,
          createdAt: true,
          updatedAt: true,
          lastLogin: true,
        },
      });

      return user as User | null;
    } catch (error) {
      console.error('根据用户名获取用户失败:', error);
      throw new Error('根据用户名获取用户失败');
    }
  }

  // 创建用户
  async createUser(data: CreateUserRequest): Promise<User> {
    try {
      // 检查用户名是否已存在
      const existingUser = await prisma.user.findFirst({
        where: {
          OR: [
            { username: data.username },
            { email: data.email || '' },
          ],
          display: true, // 只检查未软删除的用户
        },
      });

      if (existingUser) {
        throw new Error('用户名或邮箱已存在');
      }

      // 加密密码
      const hashedPassword = await hashPassword(data.password);

      // 创建用户
      const user = await prisma.user.create({
        data: {
          username: data.username,
          email: data.email || null,
          password: hashedPassword,
          role: data.role || 'user',
          status: data.status !== undefined ? data.status : true,
        },
        select: {
          id: true,
          username: true,
          email: true,
          password: true,
          role: true,
          status: true,
          display: true,
          deleteBy: true,
          deleteAt: true,
          createdAt: true,
          updatedAt: true,
          lastLogin: true,
        },
      });

      return user as User;
    } catch (error) {
      console.error('创建用户失败:', error);
      if (error instanceof Error) {
        throw error;
      }
      throw new Error('创建用户失败');
    }
  }

  // 更新用户
  async updateUser(id: number, data: UpdateUserRequest): Promise<User> {
    try {
      // 检查用户是否存在
      const existingUser = await this.getUserById(id);
      if (!existingUser) {
        throw new Error('用户不存在');
      }

      // 如果要更新用户名或邮箱，检查是否重复
      if (data.username || data.email) {
        const duplicateUser = await prisma.user.findFirst({
          where: {
            AND: [
              { id: { not: id } },
              {
                OR: [
                  { username: data.username },
                  { email: data.email },
                ],
              },
            ],
            display: true, // 只检查未软删除的用户
          },
        });

        if (duplicateUser) {
          throw new Error('用户名或邮箱已存在');
        }
      }

      // 准备更新数据
      const updateData: any = {
        username: data.username,
        email: data.email,
        role: data.role,
        status: data.status,
      };

      // 如果提供了新密码，进行加密
      if (data.password) {
        updateData.password = await hashPassword(data.password);
      }

      // 执行更新
      const user = await prisma.user.update({
        where: { id },
        data: updateData,
        select: {
          id: true,
          username: true,
          email: true,
          password: true,
          role: true,
          status: true,
          display: true,
          deleteBy: true,
          deleteAt: true,
          createdAt: true,
          updatedAt: true,
          lastLogin: true,
        },
      });

      return user as User;
    } catch (error) {
      console.error('更新用户失败:', error);
      if (error instanceof Error) {
        throw error;
      }
      throw new Error('更新用户失败');
    }
  }

  // 软删除用户
  async deleteUser(id: number, deleteBy?: number): Promise<void> {
    try {
      // 检查用户是否存在
      const existingUser = await this.getUserById(id);
      if (!existingUser) {
        throw new Error('用户不存在');
      }

      // 执行软删除
      await prisma.user.update({
        where: { id },
        data: {
          display: false,
          deleteBy: deleteBy || null,
          deleteAt: new Date(),
        },
      });
    } catch (error) {
      console.error('删除用户失败:', error);
      if (error instanceof Error) {
        throw error;
      }
      throw new Error('删除用户失败');
    }
  }

  // 更新用户最后登录时间
  async updateLastLogin(id: number): Promise<void> {
    try {
      await prisma.user.update({
        where: { id },
        data: { lastLogin: new Date() },
      });
    } catch (error) {
      console.error('更新最后登录时间失败:', error);
      throw new Error('更新最后登录时间失败');
    }
  }

  // 获取用户统计信息
  async getUserStats(): Promise<{
    total: number;
    active: number;
    inactive: number;
    admin: number;
    editor: number;
    user: number;
  }> {
    try {
      const [total, active, inactive, admin, editor, user] = await Promise.all([
        prisma.user.count({ where: { display: true } }),
        prisma.user.count({ where: { display: true, status: true } }),
        prisma.user.count({ where: { display: true, status: false } }),
        prisma.user.count({ where: { display: true, role: 'admin' } }),
        prisma.user.count({ where: { display: true, role: 'editor' } }),
        prisma.user.count({ where: { display: true, role: 'user' } }),
      ]);

      return {
        total,
        active,
        inactive,
        admin,
        editor,
        user,
      };
    } catch (error) {
      console.error('获取用户统计失败:', error);
      throw new Error('获取用户统计失败');
    }
  }

  // 检查用户名是否可用
  async isUsernameAvailable(username: string, excludeId?: number): Promise<boolean> {
    try {
      const where: any = {
        username,
        display: true,
      };

      if (excludeId) {
        where.id = { not: excludeId };
      }

      const user = await prisma.user.findFirst({ where });
      return !user;
    } catch (error) {
      console.error('检查用户名可用性失败:', error);
      throw new Error('检查用户名可用性失败');
    }
  }

  // 检查邮箱是否可用
  async isEmailAvailable(email: string, excludeId?: number): Promise<boolean> {
    try {
      const where: any = {
        email,
        display: true,
      };

      if (excludeId) {
        where.id = { not: excludeId };
      }

      const user = await prisma.user.findFirst({ where });
      return !user;
    } catch (error) {
      console.error('检查邮箱可用性失败:', error);
      throw new Error('检查邮箱可用性失败');
    }
  }
}
